<?php

namespace app\api\controller;

use addons\shopro\job\OrderAutoOper;
use addons\shopro\model\Cats;
use addons\shopro\model\User;
use app\admin\model\AdminLog;
use app\admin\model\CatOrder;
use app\common\controller\Api;
use addons\shopro\listener\order\Send;
use app\common\library\Sms as Smslib;
use app\common\model\MiUserAliyun;
use think\Cache;
use think\Db;
use think\Hook;
use think\Loader;
use think\queue\Job;
use baofu\Util\Log;

Loader::import('aliapo.AopClientSelf', APP_PATH . '../addons/alilogin/extend/');
Loader::import('aliapo.AopClient', APP_PATH . '../addons/alilogin/extend/');
Loader::import('aliapo.request.AlipaySystemOauthTokenRequest', APP_PATH . '../addons/alilogin/extend/');
Loader::import('aliapo.request.AlipayUserAgreementPageSignRequest', APP_PATH . '../addons/alilogin/extend/');
Loader::import('aliapo.request.AlipayTradeCreateRequest', APP_PATH . '../addons/alilogin/extend/');
Loader::import('aliapo.request.AlipayTradePayRequest', APP_PATH . '../addons/alilogin/extend/');
Loader::import('aliapo.request.AlipayTradeAppPayRequest', APP_PATH . '../addons/alilogin/extend/');
Loader::import('aliapo.request.AlipayUserAgreementUnsignRequest', APP_PATH . '../addons/alilogin/extend/');
Loader::import('aliapo.request.AlipayTradeRefundRequest', APP_PATH . '../addons/alilogin/extend/');
Loader::import('aliapo.request.AlipayUserAgreementQueryRequest', APP_PATH . '../addons/alilogin/extend/');

/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
//    protected $noNeedLogin = ['test', 'test1', 'login', 'setUserInfoAli', 'saveMobile', 'auth'];
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];

    protected $appId;
    protected $gatewayUrl;
    protected $rsaPrivateKey;
    protected $alipayrsaPublicKey;

    public function __construct()
    {
        //本人
//        $this->appId = '2021004109636192';//支付宝appid
//        $this->gatewayUrl = 'https://openapi.alipay.com/gateway.do';//支付宝网关
//        $this->rsaPrivateKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCBBzJugFg+BTTt0NtAW4tVEcMRwhBM1YtsjxgKh1bi/IW8zfeDq1R7SKaoiZ7xonCblgioaaTbFYS2Xleb3L5POBAdIdA01mRYKSzjn1gsod+TYGAi6d+GWNbC73IFCgaqr6cd6niSkCQ3OMcmC0JY0Zueq+5K/lpddVVlXH7s/sqAd6KIUqrfmaDa/tLzig42qjTg60zqSNWbaTsYMNQt6FvuCuQW9/RNnJ1vuImpjn/sniRSkUPsJ2UXNI1+gDmjBv8wgXofdoneySOMgRFZXCJSsBjs8aqnHxe5WUqEURRs5G4X1OjipT7CXW/qCtDk9tJhX2o7Biy59tEvxTklAgMBAAECggEAQxwiL/VTcFa28+bI0w2KR+HoKwlb/wqm7Pz0TS2dlIwxZ0Vdsr9fPoxIGqsR365UkagUsrvYAheMImqpeKj01zFauDxJFeJY6L3p2i6b5wL+zaG3/xDTsQXuFhACpvpTA14/NsEom1qba5l9g50hkh7bqUjVtW3cRHXtx723Sr5xb10D/BtQV56R9zYKeGp+czCH4A6M1VEoYCKhub1KNrmdL68fJkPFF4G1LQ46+lLHmRCSuXIiXQYsOcSyaKdps5z+YsFFyqTnez7UGDQqgQTGsF2tLrzsAMzCh6DctR7+YLTCmEZFhg4LrmXr/sGTZjxFOsC3bmzGNUmeJX0fVQKBgQDHDDnwY3nL0Zc9K6Cf7Go1UYzD+u/AUkionMNQlBICE3Xz1tUoSBLJ6NyZ+bYIbaxe3NW+VlE53dUhfyp1VPsw3DMKPLyG1Y1yUGUV8l9OVA31AKoRIp8dNXzl0OCBOSGKDju3JV8FWQV/IOZhKjzXax3nyEk55xXRs0yIIIZUSwKBgQCl8jLXTa9y/6DCjjIE7URezdsn0dwPTVtf1icwqoE/6tGL4cuKbP4t69hNyoiyXIguHZPnWSrW5TLx1LMpnP2ArT42CZbJ4MzUiLu7avNtFIbEv1Tp1DwyVREK/q8czqON4wSGRfW4qr1c/Q4MECEcd6Y6ArfMnS1AQHFB2VXiTwKBgEtNytWxLLD5eDhCOyCFtqC5W4IBe5bNCoQP2qyveCik6Cj6C+aTbdhJarwuBrolk+LHtW2vBkfYLvvfOlbtcaLIi97Bn6l7PWoUFEo7Sec+UZFxUOXurTfFtpzTazw4OwIZ5Gmjj9FcHoI8FiyIaEAvXD8GPP3U+SI+rSOK+ocFAoGBAIUL6jc00bYhvYI+/1tz350i7tK+LvEV1GzCBim+imH0oozEO6yANkobDRFRkMdv6L8Qd8TEeNRSbsX1ArAabiT8wSQSDBNPaOn9toZM+V47VtHnlOzkfF7eVQu7pioygm7/1GDTNm8YdTpYqSqCxAlO5Lcd9r7WRbF9+VASMAmBAoGAJV5RKkhuaLHZALEdHUk5/87rBEz0xgHzLvoy2lCKYOXqZVgo/oe/UqYbkuyX/8CVVJSG4H3c7+A+56HPQI9T8gxLlJqt5XrsuqFZje5LsFg2ka0pE61NbaYjEnxhtT7Jp7xRVms6wdAAQptNyh7kSbn2rDxy5E+hTbIKc1bsz94=';
//        $this->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmOdHAOULrOQiG2yMiY2qyKohjQSCmhBR07itH+Hdic+qkQUnhqDztnB7iqW8nL3SA3An0s/uesObl2JPkz2dj2AibkuP8GEnJ9HrlSe5vYgqv7WftTlI2RyHsC6mo7cu1Stfwrva+qXMP0ynGJo3sy/hKMu8ZgeJbYO4ZRSE8UvUnUhWl7xiZxkqt8/vSAEDnvzFo0vWzioNAVtRw+NA6LpDuQGYnLSZxPEfafTwS5DXTFke0UWTsO4Ms8hxmO1MZGcIaHlEsaE/Jl7Z/YXnwDm4GstmrTJsPpl898KkFBHfj0LCNiSm0IPHKXjct5dYa66h/hHL4K6hszdzLKHPpQIDAQAB';//应用公钥
//        parent::__construct();
        //客户
        $this->appId = '2021004100696998';//支付宝appid
        $this->gatewayUrl = 'https://openapi.alipay.com/gateway.do';//支付宝网关
        $this->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCPrUGUxHEeAZ/FQcese6vI/H4+lXwOaTSzJMRHRzAEY5105xGIvFJRcxfvd1IQJIgEI951mbny9hbqy2lfAo1ocA8epzfmBcSgZVWhT5uq5gdcql6NnLZZLOdANdo8cdpLRtRdYswrpUzk4PWC9SlGmDS3Vzs0Oi3r3RT4vlMgnOo9+HScyQeWg9X8ivf7XFZ4eF3k/hfBt7Na8pxi+iNwWLsVA4ZFdjaryUaj59R3/4ugwMjWuIaokJ54Oq9+5e7vref91PYQ1ewkR0G0sXDFUkbVmnP+8/6Rb4kpMHv26uINgBm39Pwyg0DVSSj+sCTL62kLz+bldDVpWT03CnjbAgMBAAECggEAe3LMJHzdDIEsvBoW7FaedWStPCzImMFAbKQsmWnLEhpdUfKwGCJnQGB5smF9ey1ISPZgz/6zzNQxQLBh6yaQRany882Ns/BEz+QBvUZfZGmc7bvc3iRGcTypvXwH9WOFwqQrF8opz16KQSYhDNKFEoj40ob68ZcDmeMtf8RYPG4NHvwnLok2lsABEuFeiglycnbqEIjGsKjwJDJmR9I3SFHMtcYK6wv1oVFUlIXg6Wq7Qna0h720H8sJURUM/g9xvjZBFpn/Qn61qLUHAysmujdw4loNRABlpaVfknE+xQR9xf51C/jKWUQHbQ541IBJX4auiuzBRgjAhKHtLuHbAQKBgQDDK3dhuBZPh9WYn+N9Ee6rkUxsMZ8vPJju++yj677P6/4zi4yRoGUHxD1UIY4vBGK5itoCOsI5BcQcgofDC/kR/CaGXD6bzr9lUPHIb3pnzUaSso2Qvf5SGpWvoNH1jD+XmeFdsTqwCAZ28NpiHhhMevH+KdosbJNdbzzB62mZQQKBgQC8dS33piYbaVk8B8hX2DwHgG3V01O/BjevoEApGcR2uIfcLmP59X7fUibysRMXRBQX4if0ojB++7yU482cHtqR4Dm1BiCkMkIPm2TAG/0duuN91AXhDZj3yVoVzHyY/dNr7+xC/mZTnMwEixJluCKrkqY6zZ0vPBqPfC/XJ0yPGwKBgQCgZIFY0nOraoNUSdont+wAHYnDxMgAhvlcNbdVQ3Ft6JDhBYdBSqKczl5kXKs/4ofL2duuR2HEgQOZNoCh/53ydNmoQ/jEDRXoCqyZP1xGIEImXwzObgWqreRkEHNcK6U7TqASYotLjVzatLeUOQ1ZFRT4/qYpKhW1jKxO5cvDwQKBgQCTlAu4KCMlSh039jw8FjgEA91/Gas2Ju9Kl+pGhUglVCIIGUfvQQDmbtXTLTlu+b/maBKz7qKdfhLSYYXsoPi2TWnDSZYcHsM+p4iBLCnNs0FcksE72MMWH1ZtRaG4yORcXRid6cxF476cPC/e+hAkXYXQ/Jz/lUiTXkO0b7DzSwKBgDOI8lQZmfB6DAMBc83Li9UoYnwVhQjdEhF4qPXdr6XddL3PfhJCtJtpET7YCsSEyGg64j7ujQZ5RKMzykeuvnPmcggo1xPxJS2miUsD0pmmgglA/COnhcJSabRhkKudjbGrun01owHxGdBGssKq/vDGQc7iIY1RorHUZ3xtbvL2';
        $this->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAg//JcX4lpmwYzNSWboIztnMKu0KsWmaCRgP5o6JlNRaIZ9TD06Fx/fsxsCCOqr6JfOfIEC7iYIOr9/jFH3yvq7202iQonIHtt0ol3v+0cLvS5Azxget1M1O/73HaIWjnjvmte60FJRUlEjmKhLyAIfMLspA98EZTXmsvl5hLEu3qMavVZOVXUmv24vlBt2azTkXGYr8ruAJa6D+L+jgcGQvpyGofHyF4sUnfkWXpn8NrtWlGtSFqS4dyTyqasFARrosNb8Q9DJpuPgpklgZGwPrIUXG6Xkb+1RDj4u3vK7DEb/mgjz/SU1Eed32Nx6xIu54J4rvpPFQICgFMj5WuHwIDAQAB';
        parent::__construct();

    }

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function test()
    {
        $this->success('返回成功', $this->request->param());
    }

    /**
     * 无需登录的接口
     *
     */
    public function testBaofuPay()
    {

//        $res = (new Send())->orderSendAfter($params['order']);
        $data = CatOrder::find(1018)->toArray();
        $res = (new OrderAutoOper())->baofuPay(['order' => $data]);
//        \think\Queue::later(100, '\addons\shopro\job\OrderAutoOper@baofuPay', $data);
//        die();

        $this->success('返回成功', ['action' => $res]);
    }

    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $this->success('返回成功', ['action' => 'test2']);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }

    //支付宝授权登录
    public function login()
    {
        $aop = new \AopClientSelf();
        $param = $this->request->param();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $request = new \AlipaySystemOauthTokenRequest();
        $request->setGrantType("authorization_code");
        $request->setCode($param['code']);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
//        $accessToken = $result->$responseNode->access_token;
        $userid = $result->$responseNode->user_id;
        $alipay_user_id = $result->$responseNode->alipay_user_id;
        $userinfo = MiUserAliyun::where(['user_id' => $userid])->find();
        if ($userinfo) {
            $Uid = $userinfo['id'];
        } else {
            $Uid = MiUserAliyun::insertGetId(['user_id' => $userid, 'alipay_user_id' => $alipay_user_id]);
        }
        $this->success('获取用户id成功', $Uid);

    }

    //支付宝签约 创建签约协议内容
    public function getOrderStr()
    {
        $param = $this->request->param();
        $mobile = $param['mobile'];
        $order_sn = $param['order_sn'];
        //获得用户信息 全系统 手机号统一
        $userInfo = \app\admin\model\User::where('mobile', $mobile)->find();
        //获得待签约订单
        $orderInfo = CatOrder::where('user_id', $userInfo['id'])
            ->where('status', 0)//订单状态:-2=交易关闭,-1=已取消,0=待签约,1=已签约,2=已完成,3已经解约
            ->where('order_sn', $order_sn)//订单编号
            ->find();
        $aop = new \AopClientSelf();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $request = new \AlipayUserAgreementPageSignRequest();
        $object = new \stdClass();
        $object->product_code = 'GENERAL_WITHHOLDING';
        $object->personal_product_code = 'CYCLE_PAY_AUTH_P';
        $object->sign_scene = 'INDUSTRY|DEFAULT_SCENE';
        $object->external_agreement_no = $orderInfo['order_sn'];//标示用户的唯一签约协议号，商家自定义
//        $object->sign_validity_period = '2m';//当前用户签约请求的协议有效周期。整形数字加上时间单位的协议有效期，从发起签约请求的时间开始算起。2m 代表2个月如果未传入，默认为长期有效
        $access_params = [
            'channel' => 'ALIPAYAPP'
        ];
        //周期规则参数，
        $period_rule_params = [
            'period_type' => 'MONTH',////周期类型枚举值为DAY和MONTH
            'period' => 1,//扣款周期数，每月扣1次
            'execute_time' => date('Y-m-d'),//商户发起首次扣款的时间
            'single_amount' => $orderInfo['month_money'],//每次发起扣款时限制的最大金额单位为元
            'total_amount' => $orderInfo['total_amount'],//周期内允许扣款的总金额，单位为元
            'total_payments' => $orderInfo['total_cycle'],//总扣款次数
        ];
        $object->access_params = $access_params;
        $object->period_rule_params = $period_rule_params;
        $json = json_encode($object);
        $request->setBizContent($json);
        $request->setNotifyUrl('https://zhouqifu.test.xingzong.tech/api/demo/notifyUrl');
        $response = $aop->sdkExecute($request);
        $response = urlencode($response);
        $insert = [
            'title' => '发起签约',
            'content' => !is_scalar($response) ? json_encode($response, JSON_UNESCAPED_UNICODE) : $response,
            'url' => substr(request()->url(), 0, 1500),
            'admin_id' => 1,
            'username' => '发起签约',
            'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            'ip' => request()->ip()
        ];
        AdminLog::insert($insert);
        $this->success('签约', $response);
    }

    //签约成功 授权回调
    public function notifyUrl()
    {
        $param = $this->request->param();
        $insert = [
            'title' => '签约成功授权回调',
            'content' => !is_scalar($param) ? json_encode($param, JSON_UNESCAPED_UNICODE) : $param,
            'url' => substr(request()->url(), 0, 1500),
            'admin_id' => 1,
            'username' => '签约成功支付宝授权回调',
            'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            'ip' => request()->ip()
        ];
        AdminLog::insert($insert);
        $order_sn = $param['external_agreement_no'];//标示用户的唯一签约协议号，商家自定义。仅签约接口传入时返回
        //获得待签约订单
        CatOrder::where('order_sn', $order_sn)
            ->where('status', 0)//订单状态:-2=交易关闭,-1=已取消,0=待签约,1=已签约,2=已完成
            ->update(['status' => 1, 'agreement_no' => $param['agreement_no'], 'cycletime' => time()]);
        $orderInfo = CatOrder::where('order_sn', $order_sn)->find();
        Cats::where('id', $orderInfo['cat_id'])->update(['type' => 0]);//猫咪改为已签约
        $this->pay($order_sn, 1);
        echo 'success';
    }

//    签约后扣款 $typeNum=1,第一次发起扣款，2第二次发起扣款
    public function pay($order_sn, $typeNum = 1)
    {
        //获得待签约订单
        $orderInfo = CatOrder::where('order_sn', $order_sn)->find();
        $aop = new \AopClient ();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $object = new \stdClass();
        $object->out_trade_no = $orderInfo['order_sn'];//商户订单编号
        $object->product_code = 'GENERAL_WITHHOLDING';////商家扣款产品码固定为GENERAL_WITHHOLDING
        $object->total_amount = $orderInfo['month_money'];//月扣款金额
        $object->subject = $orderInfo['cat_code'];//订单标题。猫咪编号
        $agreement_params = new \stdClass();
        $agreement_params->agreement_no = $orderInfo['agreement_no'];//协议号
        $object->agreement_params = $agreement_params;
        // 返回参数选项
        $queryOptions = [
            'fund_bill_list',
            'voucher_detail_list'
        ];
        $object->query_options = $queryOptions;
        $json = json_encode($object);
        $request = new \AlipayTradePayRequest();
        $request->setBizContent($json);
        $result = $aop->execute($request);
        if ($result->alipay_trade_pay_response->code == 10000) {
            //第一期扣款成功
            //剩余周期减一 remaining_cycle
            CatOrder::where('order_sn', $order_sn)->setDec('remaining_cycle', 1);
            CatOrder::where('order_sn', $order_sn)->update(['status' => 4, 'paytime' => time(), 'repayment' => date('d')]);
            $this->success('扣款成功', $result->alipay_trade_pay_response->fund_bill_list);
        } else {
            if ($typeNum == 1) {
                // 扣款失败后 1个小时内再次发起
                $data = ['order_sn' => $order_sn,];
                Hook::listen('order_payed_after', $data);
            } elseif ($typeNum == 2) {
                CatOrder::where('order_sn', $order_sn)->setInc('overdue_num', 1);//逾期次数加1
                //第二次失败直接解约
                $this->unsign($order_sn);
            }

            CatOrder::where('order_sn', $order_sn)->update(['status' => 6, 'updatetime' => time()]);//扣款失败
            $this->error($result->alipay_trade_pay_response->sub_msg);
        }
    }

    //计划任务：每个月主动发起扣款（已经签约的客户）
    public function activePay()
    {
        $orders = CatOrder::where('status', 'in', '1,4')
            ->where('remaining_cycle', '>', 0)
            ->select();//已经签约或者已经支付的，有剩余周期的订单
        foreach ($orders as $value) {
//            if($value['cycletime']<)
            $aop = new \AopClient ();
            $aop->gatewayUrl = $this->gatewayUrl;
            $aop->appId = $this->appId;
            $aop->rsaPrivateKey = $this->rsaPrivateKey;
            $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset = 'utf-8';
            $aop->format = 'json';
            $object = new \stdClass();
            $object->out_trade_no = $value['order_sn'];//商户订单编号
            $object->product_code = 'GENERAL_WITHHOLDING';////商家扣款产品码固定为GENERAL_WITHHOLDING
            $object->total_amount = $value['month_money'];//月扣款金额
            $object->subject = $value['cat_code'];//订单标题。猫咪编号
            $agreement_params = new \stdClass();
            $agreement_params->agreement_no = $value['agreement_no'];//协议号
            $object->agreement_params = $agreement_params;
            // 返回参数选项
            $queryOptions = [
                'fund_bill_list',
                'voucher_detail_list'
            ];
            $object->query_options = $queryOptions;
            $json = json_encode($object);
            $request = new \AlipayTradePayRequest();
            $request->setBizContent($json);
            $result = $aop->execute($request);
            $insert = [
                'title' => '用户每月扣款返回参数',
                'content' => !is_scalar($result) ? json_encode($result, JSON_UNESCAPED_UNICODE) : $result,
                'url' => substr(request()->url(), 0, 1500),
                'admin_id' => 1,
                'username' => $value['user_id'],
                'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
                'ip' => request()->ip()
            ];
            AdminLog::insert($insert);
            if ($result->alipay_trade_pay_response->code == 10000) {
                //第一期扣款成功
                //剩余周期减一 remaining_cycle
                CatOrder::where('order_sn', $value['order_sn'])->setDec('remaining_cycle', 1);
                CatOrder::where('order_sn', $value['order_sn'])->update(['status' => 4, 'paytime' => time()]);
            } else {
                CatOrder::where('order_sn', $value['order_sn'])->setInc('overdue_num', 1);//逾期次数加1
                $this->error($result->alipay_trade_pay_response->sub_msg);
            }

        }
    }


    //用户解约,商户解约（如果api设置就不走这里） 通知
    public function notify()
    {
        $param = $this->request->param();
        $insert = [
            'title' => '用户解约',
            'content' => !is_scalar($param) ? json_encode($param, JSON_UNESCAPED_UNICODE) : $param,
            'url' => substr(request()->url(), 0, 1500),
            'admin_id' => 1,
            'username' => '用户解约',
            'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            'ip' => request()->ip()
        ];
        AdminLog::insert($insert);
        $order_sn = $param['external_agreement_no'];//标示用户的唯一签约协议号，商家自定义。仅签约接口传入时返回
        //解约
        CatOrder::where('order_sn', $order_sn)->update(['status' => 3, 'unsign' => 1]);//1用户解约，2商户解约
        echo 'success';
    }

    //商户主动发起解约（后台订单管理）
    public function unsign($order_sn)
    {
        $orderInfo = CatOrder::where('order_sn', $order_sn)->where('status', 1)->find();
        $aop = new \AopClientSelf();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $request = new \AlipayUserAgreementUnsignRequest();
        $object = new \stdClass();
        $object->personal_product_code = 'CYCLE_PAY_AUTH_P';
        $object->sign_scene = 'INDUSTRY|DEFAULT_SCENE';
        $object->external_agreement_no = $orderInfo['order_sn'];
        $object->agreement_no = $orderInfo['agreement_no'];
        $object->operate_type = 'confirm';
        $json = json_encode($object);
        $request->setBizContent($json);
        $request->setNotifyUrl('https://zhouqifu.test.xingzong.tech/api/demo/notifyUnsign');//商户解约地址
        $result = $aop->execute($request);
        if ($result->alipay_user_agreement_unsign_response->code === 10000) {
            //解约
            return $result->alipay_user_agreement_unsign_response->code;
        } else {
            return $result->alipay_user_agreement_unsign_response->sub_msg;
        }
    }

    //商户解约 回调
    public function notifyUnsign()
    {
        $param = $this->request->param();
        $insert = [
            'title' => '商户解约解约',
            'content' => !is_scalar($param) ? json_encode($param, JSON_UNESCAPED_UNICODE) : $param,
            'url' => substr(request()->url(), 0, 1500),
            'admin_id' => 1,
            'username' => '用户解约',
            'useragent' => substr(request()->server('HTTP_USER_AGENT'), 0, 255),
            'ip' => request()->ip()
        ];
        AdminLog::insert($insert);
        $order_sn = $param['external_agreement_no'];//标示用户的唯一签约协议号，商家自定义。仅签约接口传入时返回
        //解约
        CatOrder::where('order_sn', $order_sn)->update(['status' => 3, 'unsign' => 2]);//1用户解约，2商户解约
        echo 'success';
    }

    //退款接口
    public function refund($order)
    {
        $aop = new \AopClientSelf();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $object = new \stdClass();
        $object->out_trade_no = $order['order_sn'];//商户订单号
        $object->refund_amount = $order['month_money'];//退款金额。 需要退款的金额
        $object->out_request_no = 'refund' . time();//退款请求号。 标识一次退款请求，需要保证在交易号下唯一，如需部分退款，则此参数必传
        $json = json_encode($object);
        $request = new \AlipayTradeRefundRequest();
        $request->setBizContent($json);
        $result = $aop->execute($request);
        if ($result->alipay_trade_refund_response->code === 10000) {
            //退款成功
            CatOrder::where('order_sn', $order['order_sn'])
                ->update(['status' => 5, 'trade_no' => $result->alipay_trade_refund_response->trade_no, 'refundtime' => time()]);
            return $result->alipay_trade_refund_response->code;
        } else {
            return $result->alipay_trade_refund_response->msg;
        }
    }

    //支付宝个人代扣协议查询
    public function AgreementQuery($order)
    {
        $aop = new \AopClient ();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $object = new \stdClass();
        $object->personal_product_code = 'CYCLE_PAY_AUTH_P';
        $object->external_agreement_no = $order['order_sn'];//订单编号
        $object->agreement_no = $order['agreement_no'];//签约编号
        $object->sign_scene = 'INDUSTRY|DEFAULT_SCENE';//签约场景码
        $json = json_encode($object);
        $request = new \AlipayUserAgreementQueryRequest ();
        $request->setBizContent($json);
        $result = $aop->execute($request);
        if ($result->alipay_user_agreement_query_response->code === 10000) {
            //协议当前状态//1. TEMP：暂存，协议未生效过；//2. NORMAL：正常；//3. STOP：暂停
            return $result->alipay_user_agreement_query_response->status;
        } else {
            return $result->alipay_user_agreement_query_response->sub_msg;
        }
    }

    /**
     * 保存支付宝好信息
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setUserInfoAli()
    {
        $Uid = Cache::get('Uid');
        $param = $this->request->param();
        return MiUserAliyun::where('user_id', $Uid)
            ->update([
                'avatar' => $param['avatar'],
                'nickname' => $param['nickName']
            ]);
    }

    //记录手机号，并通过手机号查询小程序端的授权
    public function saveMobile()
    {
        $aesKey = "w65axMaHgemkKsUqfiMJRQ==";//AES密钥
        $param = $this->request->param();
        $content = $param['response']; // 从小程序获取的加密数据
        $Uid = $param['uid'] ?? 0; // 从小程序获取的加密数据
        $result = openssl_decrypt(base64_decode($content), 'AES-128-CBC', base64_decode($aesKey), OPENSSL_RAW_DATA);
        $mobile = json_decode($result, true);
        $where['mobile'] = $mobile['mobile'];
        $user = MiUserAliyun::where('id', $Uid)->find();
        if (empty($user)) {
            $this->error('登录失败，请先授权');
        } else {
            MiUserAliyun::where('id', $Uid)->update(['mobile' => $mobile['mobile']]);
            //查看该手机号是否已经在微信小程序中注册
            $user = \app\admin\model\User::where($where)->find();
            if (empty($user)) {
                $this->error('请确认手机号是否为猫下单手机号');
            } else {
                $this->auth->direct($user['id']);
                $this->success('获得手机号成功', $this->auth->getUserinfo());
            }
        }
    }


    /**
     * 获取支付宝用户信息
     * @param $accessToken
     */
    protected function getUserInfoAli($accessToken)
    {
        $aop = new \AopClientSelf();
        $aop->gatewayUrl = $this->gatewayUrl;
        $aop->appId = $this->appId;
        $aop->rsaPrivateKey = $this->rsaPrivateKey;
        $aop->alipayrsaPublicKey = $this->alipayrsaPublicKey;
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $request = new \AlipayUserInfoShareRequestSelf ();
        $result = $aop->execute($request, $accessToken);
        return $result;
    }

    /**
     * 测试宝付扣款
     * @param Job $job
     * @param $data
     * @return void
     */
    public function baofuPay()
    {
        $id = 1031;
        //获得待签约订单
        $orderInfo = CatOrder::where('id', $id)->find();
        // $pay_time = getNextMonthDays($orderInfo);
        // var_dump($pay_time);die;
        \think\Queue::later(2, '\addons\shopro\job\OrderAutoOper@baofuPay_cs', ['order' => $orderInfo], 'shopro');
        
        
        
        // $paytime = getNextMonthDays1($orderInfo);
        //                         write_log('订单id为' . $orderInfo['id'] . '，调用方法为baofuPay，支付结果为success，下次扣款时间：' . date('Y-m-d H:i:s', $paytime), 'baofuPay');
        //                         \think\Queue::later($paytime - time(), '\addons\shopro\job\OrderAutoOper@baofuPay', ['order' => $orderInfo], 'shopro');
        
        // $paytime = getNextMonthDays($orderInfo);
        // var_dump($paytime);die;
        // $mobile = Db::name('user_baofu_bank')->where('protocol_no', $orderInfo['protocol_no'])->value('phone');
        // Smslib::notice($mobile, '', 'sending_2');

        // $time = strtotime(date("Y-m-d", strtotime("+1 day")));
        // var_dump($time);die;
        // $mobile = 15316304701;
        // Smslib::notice($mobile, '', 'sending_3');
        // Smslib::notice($mobile, '', 'sending_1');
        // Smslib::notice($mobile, '', 'sending_2');
        // Smslib::notice($mobile, '', 'sending_3');
        // \think\Queue::later(2, '\addons\shopro\job\OrderSms@sending_sms', ['order' => $orderInfo], 'shopro');
//        getNextMonthDays($orderInfo);
//        $paytime = time();
//        CatOrder::where('id', $id)->setDec('remaining_cycle', 1);
//
//        //检查当前剩余扣款周期
//        $info = CatOrder::where('id', $id)->value('remaining_cycle');
//        if ($info != 0) {
//            //下期期数
//            $cycle = ($orderInfo['total_cycle'] - $info) + 1;
//            var_dump($cycle);
//            die;
//            //获取下个月的时间
//            $paytime = strtotime(getNextMonthDays($orderInfo['deduction_time'], $cycle) . ' 9:0:0');
//        }
//        $info = $orderInfo['remaining_cycle'];
//        $time = $orderInfo['createtime'];
//        $day = date('d', $time);
//        $deduction_day = $orderInfo['deduction_day'];
//        $first_month = date("Y-m", $time);
//        if ($deduction_day < $day) {
//            // 下个月
//            $first_month = date("Y-m", strtotime("+1 month", $time));
//        }
//
//        $cycle = $orderInfo['total_cycle'] - $info;
//        $pay_month = date("Y-m", strtotime("+" . $cycle . " month", strtotime($first_month)));
//        $pay_time = strtotime($pay_month . '-' . $deduction_day);
//        \think\Queue::later(($pay_time - $time), '\addons\shopro\job\OrderAutoOper@baofuPay', ['order' => $orderInfo], 'shopro');

        //发送短信
//        $smstime = strtotime("-3 days", $pay_time);
//        if ($smstime <= $time) {
//            // 立即发送
////            \think\Queue::later(2, '\addons\shopro\job\OrderSms@sending_sms', ['order' => $orderInfo], 'shopro');
//        } else {
//            $times = $smstime - $time;
//            //$times = 60 * 10;
////            \think\Queue::later($times, '\addons\shopro\job\OrderSms@sending_sms', ['order' => $orderInfo], 'shopro');
//        }



    }
}
